import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes = [
  { path: '/login', name: 'login', component: () => import('@/views/login.vue') },
  {
    path: '/',
    name: 'home',
    component: () => import('@/layout/index.vue'),
    redirect: { name: 'proj.list' },
    children: [
      {
        path: 'proj/list',
        name: 'proj.list',
        component: () => import('@/views/proj/list.vue'),
        redirect: { name: 'section.list', params: { id: 1 } },
        children: [
          { path: 'section-list/:id', name: 'section.list', component: () => import('@/views/section/list.vue') },
        ],
      },
    ],
  },
] as RouteRecordRaw[]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach((to) => {
  const token = localStorage.getItem('token')
  if (!token && to.name !== 'login') {
    return { name: 'login' }
  }
})

export default router
